//
//  DAUploadBookViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/6/1.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAUploadBookViewController.h"
#import "Utility.h"
#import "DAHeader.h"
#import "DAKit.h"
#import "DADataHandel.h"
#import "DABookType.h"
#import "SVProgressHUD.h"
#import "DAloginPersonalInformation.h"

@interface DAUploadBookViewController()<UITextFieldDelegate,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource>{
    NSData *imageData;
    UIView *backView;
    NSArray *typeArray;
    NSString *bookType;
}
@property (weak, nonatomic) IBOutlet UITextField *bookNameTF;
@property (weak, nonatomic) IBOutlet UILabel *bookNameLabel;

@property (weak, nonatomic) IBOutlet UITextField *bookCodeTF;
@property (weak, nonatomic) IBOutlet UILabel *bookCodeLabel;
@property (weak, nonatomic) IBOutlet UITextField *bookTypeTF;
@property (weak, nonatomic) IBOutlet UILabel *bookTypeLabel;
@property (weak, nonatomic) IBOutlet UITextView *bookIntroTV;
@property (weak, nonatomic) IBOutlet UILabel *bookIntroLabel;
@property (weak, nonatomic) IBOutlet UIImageView *bookImage;
@property (weak, nonatomic) IBOutlet UIImageView *cameraImage;
@property (weak, nonatomic) IBOutlet UIButton *bookTypeButton;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;
- (IBAction)onTouchConfirm:(id)sender;
- (IBAction)onTouchType:(id)sender;

@end
@implementation DAUploadBookViewController
-(void)viewDidLoad{
    [super viewDidLoad];
    NSString *upload = NSLocalizedString(@"isUpload", nil);
    self.title = upload;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationController.navigationBar.barTintColor = [UIColor supportGreenColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.tableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissKeyboard)];
    [self.tableView addGestureRecognizer:tap];
    self.tableView.userInteractionEnabled = YES;
    
    [self configureCell];
    [self prepareData];
}

#pragma mark - 数据准备
- (void)prepareData{
    /** 取出图书所有类型*/
    NSString *URL= DABookTypeURL;
    [DADataHandel postURL:URL parame:nil cookie:nil result:^(id result) {
        if (result && [result isKindOfClass:[NSDictionary class]]) {
            // 图书类型
            DABookType *bookTypeModel = [[DABookType alloc]init];
            typeArray = [bookTypeModel returnModelInArrayWithDic:result[@"result"]];
        }else{
            NSLog(@"DABookTypeURL:数据异常。");
        }
    }];
}

- (void)dismissKeyboard{
    [self.bookNameTF resignFirstResponder];
    [self.bookCodeTF resignFirstResponder];
    [self.bookTypeTF resignFirstResponder];
    [self.bookIntroTV resignFirstResponder];
}

- (void)configureCell{
    
    NSString *inputBookName = NSLocalizedString(@"inputBookName", nil);
    NSString *inputBookBarCode = NSLocalizedString(@"inputBookBarCode", nil);
    NSString *isChooseBookType = NSLocalizedString(@"isChooseBookType", nil);
    NSString *inputBookIntroduction = NSLocalizedString(@"inputBookIntroduction", nil);
    NSString *submit = NSLocalizedString(@"submit", nil);
    NSString *bookName = NSLocalizedString(@"bookName", nil);
    NSString *bookCode = NSLocalizedString(@"bookCode", nil);
    NSString *booktype = NSLocalizedString(@"booktype", nil);
    NSString *bookIntro = NSLocalizedString(@"bookIntro", nil);
    
    self.bookNameLabel.text = bookName;
    self.bookCodeLabel.text = bookCode;
    self.bookTypeLabel.text = booktype;
    self.bookIntroLabel.text = bookIntro;
    self.bookImage.hidden = YES;
    self.bookNameTF.placeholder = inputBookName;
    self.bookCodeTF.placeholder = inputBookBarCode;
    self.bookTypeTF.placeholder = isChooseBookType;
    self.bookNameTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.bookCodeTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.bookCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    [self.bookIntroTV.layer setBorderColor:[UIColor colorWithHexString:@"#cccccc"].CGColor];
    [self.bookIntroTV.layer setBorderWidth:0.5];
    [self.bookIntroTV.layer setCornerRadius:5];
    self.bookIntroTV.text = inputBookIntroduction;
    self.bookIntroTV.textColor = [UIColor colorWithHexString:@"#cccccc"];
    self.bookIntroTV.delegate = self;
    self.confirmButton.backgroundColor = [UIColor supportGreenColor];
    [self.confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.confirmButton setTitle:submit forState:UIControlStateNormal];
    [self.confirmButton.layer setCornerRadius:5];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTouchImage)];
    [self.cameraImage addGestureRecognizer:tap];
    self.cameraImage.userInteractionEnabled = YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    NSString *inputBookIntroduction = NSLocalizedString(@"inputBookIntroduction", nil);
    if([textView.text isEqualToString:inputBookIntroduction]){
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }else{
        textView.textColor = [UIColor colorWithHexString:@"#cccccc"];
    }
}
#pragma mark - textFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [self dismissPicker];;
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    [self dismissPicker];
    NSString *inputBookIntroduction = NSLocalizedString(@"inputBookIntroduction", nil);
    if([textView.text isEqualToString:@""]){
        textView.text = inputBookIntroduction;
        textView.textColor = [UIColor colorWithHexString:@"#cccccc"];
    }
    if([textView.text isEqualToString:inputBookIntroduction]){
        textView.textColor = [UIColor colorWithHexString:@"#cccccc"];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(indexPath.section ==0 && indexPath.row > 4){
        cell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    }
}

#pragma mark - ShowAlert
- (void)showAlertWithContent:(NSString *)content{
    [self dismissKeyboard];
    [self dismissPicker];
    NSString *takePhoto = NSLocalizedString(@"takePhoto", nil);
    NSString *photoAlbum = NSLocalizedString(@"photoAlbum", nil);
    NSString *cancel = NSLocalizedString(@"cancel", nil);
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:content preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *TopAction = [UIAlertAction actionWithTitle:takePhoto style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        /** 调用拍照上传*/
        [self chooseTakePhoto];
    }];
    UIAlertAction *midAction = [UIAlertAction actionWithTitle:photoAlbum style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        /** 调用相册*/
        [self choosePhotoLibrary];
    }];
    UIAlertAction *bottom = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:TopAction];
    [alert addAction:midAction];
    [alert addAction:bottom];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 选择相册上传
- (void)choosePhotoLibrary{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    picker.delegate = self;
    picker.allowsEditing = NO;
    [self presentViewController:picker animated:YES completion:^{
    }];
}
#pragma mark - 选择拍照上传
- (void)chooseTakePhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    picker.delegate = self;
    picker.allowsEditing = NO;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    [self presentViewController:picker animated:YES completion:^{}];
}
#pragma mark - 相册的协议方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (image != nil ) {
    // 压缩图片
   // CGSize imageSize = self.bookImage.image.size;
    CGFloat targetWidth = 200;
    CGFloat targetHeight = 200 ;
    
    CGSize newSize = CGSizeMake(targetWidth, targetHeight);
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
        self.cameraImage.image = nil;
        self.bookImage.hidden = NO;
        self.bookImage.image = newImage;
    if (UIImagePNGRepresentation(newImage)) {
        imageData = UIImagePNGRepresentation(newImage);
    }else{
        imageData = UIImageJPEGRepresentation(newImage, 1.0);
    }
    }
    [self dismissViewControllerAnimated:YES completion:^{

    }];
}

- (void)onTouchImage{
    NSString *bookImageUpload = NSLocalizedString(@"isUploadBookCover", nil);
    [self showAlertWithContent:bookImageUpload];
}

- (IBAction)onTouchConfirm:(id)sender {
    NSString *bookImageUpload = NSLocalizedString(@"pleaseUploadBookCover", nil);
    NSString *sure = NSLocalizedString(@"Sure", nil);
   // NSString *cancel = NSLocalizedString(@"cancel", nil);
    if(imageData.length == 0){
        [DAAlertView showDAAlertWithPositionType:DAAlertDisplayerPositionTypeCenter animationType:DAAlertDisplayerShowTypeBounce titleText:@"提示" contentText:bookImageUpload cancelButtonTitle:sure buttonList:nil handleActionBlock:^(DAAlertView *displayer, NSInteger index) {}];
        return;
    }
    if(self.bookNameTF.text.length == 0){
        [DAAlertView showDAAlertWithPositionType:DAAlertDisplayerPositionTypeCenter animationType:DAAlertDisplayerShowTypeBounce titleText:@"提示" contentText:self.bookNameTF.placeholder cancelButtonTitle:sure buttonList:nil handleActionBlock:^(DAAlertView *displayer, NSInteger index) {}];
        return;
    }
    if(self.bookCodeTF.text.length == 0){
        [DAAlertView showDAAlertWithPositionType:DAAlertDisplayerPositionTypeCenter animationType:DAAlertDisplayerShowTypeBounce titleText:@"提示" contentText:self.bookCodeTF.placeholder cancelButtonTitle:sure buttonList:nil handleActionBlock:^(DAAlertView *displayer, NSInteger index) {}];
        return;
    }
    if(self.bookTypeTF.text.length == 0){
        [DAAlertView showDAAlertWithPositionType:DAAlertDisplayerPositionTypeCenter animationType:DAAlertDisplayerShowTypeBounce titleText:@"提示" contentText:self.bookTypeTF.placeholder cancelButtonTitle:sure buttonList:nil handleActionBlock:^(DAAlertView *displayer, NSInteger index) {}];
        return;
    }
    NSString *introString;
    NSString *inputBookIntroduce = NSLocalizedString(@"inputBookIntroduction", nil);
    if([self.bookIntroTV.text isEqualToString:inputBookIntroduce]){
        introString = @"";
    }else{
        introString = self.bookIntroTV.text;
    }
    NSString *base64String = [imageData base64EncodedStringWithOptions:0];
    
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES).lastObject stringByAppendingString:@"DALogin"];
    DAloginPersonalInformation *personalInformation = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    NSDictionary *dic = @{@"userID": personalInformation.userID,@"bookName": self.bookNameTF.text,@"bookCode": self.bookCodeTF.text,@"bookType": bookType,@"bookIntro": introString,@"bookImage": base64String};
    NSString *isUploading = NSLocalizedString(@"isUploading", nil);
    NSString *isUploadingSuccess = NSLocalizedString(@"isUploadingSuccess", nil);
    NSString *isUploadingFailed = NSLocalizedString(@"isUploadingFailed", nil);
    [SVProgressHUD showWithStatus:isUploading];
    [DADataHandel postURL:DABookUploadURL parame:dic cookie:nil result:^(id result) {
        if(result && [result isKindOfClass:[NSDictionary class]]){
            if([result[@"result"]isEqualToString:@"true"]){
                [SVProgressHUD showSuccessWithStatus:isUploadingSuccess];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self dismissViewControllerAnimated:YES completion:nil];
                });
                
            }else{
                [SVProgressHUD showErrorWithStatus:isUploadingFailed];
            }
        }else{
             NSLog(@"DABookUploadURL:数据异常。");
        }
    }];
}

#pragma mark - picker
- (IBAction)onTouchType:(id)sender {
    if(typeArray.count > 0){
        DABookType *type = typeArray[0];
        self.bookTypeTF.text = type.bookTypeName;
        bookType = type.bookTypeId;
    }
    [self dismissKeyboard];
    backView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    backView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissPicker)];
    [backView addGestureRecognizer:tap];

    UIPickerView *pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height, SCREENWIDTH, 200)];
    pickerView.dataSource = self;
    pickerView.delegate = self;
    pickerView.backgroundColor = [UIColor whiteColor];
    [[UIApplication sharedApplication].keyWindow addSubview:backView];
    [backView addSubview:pickerView];
    [UIView animateWithDuration:0.3 animations:^{
        pickerView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-200, SCREENWIDTH, 200);
    }];
}

-(void)dismissPicker{
    [backView removeFromSuperview];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return typeArray.count;
}
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    DABookType *type = typeArray[row];
    return type.bookTypeName;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    DABookType *type = typeArray[row];
    bookType = type.bookTypeId;
    self.bookTypeTF.text = type.bookTypeName;
}

@end
